﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.IO;
using mesoBoard.Data;
using mesoBoard.Data.Repositories;
using System.Drawing.Imaging;
using System.Drawing;

namespace mesoBoard.Services
{
    public class Global : IGlobal
    {
         
        private IRepositoriesWrapper Repositories;

        public Global(IRepositoriesWrapper repos)
        {
            this.Repositories = repos;
        }

        public void PruneOnlineGuests()
        {
            Repositories.OnlineUsers.PruneOnlineGuests();
        }

        public void PruneOnlineUsers()
        {
            Repositories.OnlineUsers.PruneOnlineUsers();
        }

        public void OnlineUserRoutine(User CurrentUser, string VisitorIP)
        {
            PruneOnlineGuests();
            PruneOnlineUsers();

            bool IsAuthenticated = CurrentUser != null && CurrentUser.UserID != 0;

            if (IsAuthenticated)
            {
                OnlineUser TheOUser = Repositories.OnlineUsers.GetOnlineUser(CurrentUser.UserID);
                OnlineGuest TheGuest = Repositories.OnlineUsers.GetOnlineGuest(VisitorIP);

                if (TheGuest != null)
                    Repositories.OnlineUsers.DeleteOnlineGuest(VisitorIP);

                if (TheOUser == null)
                {
                    Repositories.OnlineUsers.CreateOnlineUser(new OnlineUser
                    {
                        UserID = CurrentUser.UserID,
                        Date = DateTime.UtcNow,
                    }
                    );
                }
                else if ((DateTime.UtcNow - TheOUser.Date).Minutes > 5)
                {
                    TheOUser.Date = DateTime.UtcNow;
                    Repositories.OnlineUsers.UpdateOnlineUser(TheOUser);
                }
            }
            else
            {
                OnlineGuest TheOGuest = Repositories.OnlineUsers.GetOnlineGuest(VisitorIP);
                if (TheOGuest == null)
                {
                    Repositories.OnlineUsers.CreateOnlineGuest(new OnlineGuest
                    {
                        IP = VisitorIP,
                        Date = DateTime.UtcNow
                    }
                    );
                }
                else if ((DateTime.UtcNow - TheOGuest.Date).Minutes > 5)
                {
                    TheOGuest.Date = DateTime.UtcNow;
                    Repositories.OnlineUsers.UpdateOnlineGuest(TheOGuest);
                }
            }

        }
    }
}